package com.zhenwei.zscm.common;

import com.zhenwei.zscm.common.annotations.MethodName;
import com.zhenwei.zscm.config.SystemConfig;
import com.zhenwei.zscm.model.dto.apiInfo.ApiInfoDTO;
import com.zhenwei.zscm.repo.ApiInfoRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PathPatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class ApiInfoScanner {
    @Autowired
    private ApiInfoRepo apiInfoRepository;
    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;
    public void scanAndSyncApiInfo() {
        if (!SystemConfig.reloadApiList) {
           return;
        }
        log.info("开始扫描程序API接口...");
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();

        List<ApiInfoDTO> apiInfoList = new ArrayList<>();

        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo requestMappingInfo = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();

            // 获取方法上的 @MethodName 注解（接口名称）
            MethodName methodNameAnnotation = handlerMethod.getMethodAnnotation(MethodName.class);
            String methodNameValue = methodNameAnnotation != null ? methodNameAnnotation.value() : "";

            // 获取控制器上的 @MethodName 注解（分组名称）
            MethodName controllerNameAnnotation = handlerMethod.getBeanType().getAnnotation(MethodName.class);
            String controllerNameValue = controllerNameAnnotation != null ? controllerNameAnnotation.value() : "";

            if (methodNameAnnotation != null && controllerNameAnnotation != null) {
                PathPatternsRequestCondition p = entry.getKey().getPathPatternsCondition();
                String apiUrl = "";
                if (p != null) {
                    apiUrl = p.getFirstPattern().getPatternString();
                }
                // 获取请求方法（GET、POST 等）
                Set<RequestMethod> requestMethods = requestMappingInfo.getMethodsCondition().getMethods();
                String requestMethod = requestMethods.isEmpty() ? "" : requestMethods.iterator().next().name();

                // 组合路由路径和请求方法作为唯一标识（避免不同请求方法但相同路径的情况）
                String uniqueIdentifier = requestMethod + "->" + apiUrl;

                ApiInfoDTO apiInfo = new ApiInfoDTO();
                apiInfo.setApiUrl(uniqueIdentifier);
                apiInfo.setApiName(handlerMethod.getMethod().getName());
                apiInfo.setApiDesc(methodNameValue);
                apiInfo.setApiGroup(controllerNameValue);

                apiInfoList.add(apiInfo);
            }
        }
        // 同步到数据库
       apiInfoRepository.insert(apiInfoList);
    }
}
